package com.li.hashtab;

import java.util.Scanner;

public class hashtabDemo {
    public static void main(String[] args) {
        HashTab hashTab = new HashTab(7);
        String key = "";
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("add:添加雇员");
            System.out.println("list:显示雇员");
            System.out.println("exit:退出系统");
            key = scanner.next();
            switch (key) {
                case "add":
                    System.out.println("输入id");
                    int id = scanner.nextInt();
                    System.out.println("请输入名字");
                    String name = scanner.next();
                    Emp emp = new Emp(id, name);
                    hashTab.add(emp);
                    break;
                case "list":
                    hashTab.list();
                    break;
                case "exit":
                    scanner.close();
                    ;
                    System.exit(0);
                default:
                    break;
            }
        }


    }
}

class Emp {
    public int id;
    public String name;
    public Emp next;

    public Emp(int id, String name) {
        this.id = id;
        this.name = name;
    }

}

//表示链表
class EmpLinckList {
    private Emp head;

    //添加雇员到链表
    public void add(Emp emp) {
        if (head == null) {
            head = emp;
            return;
        }
        Emp curEmp = head;
        while (true) {
            if (curEmp.next == null) {
                break;
            }
            curEmp = curEmp.next;
        }
        curEmp.next = emp;
    }

    public void list() {
        if (head == null) {
            System.out.println("当前链表为空");
            return;
        }
        Emp curemp = head;
        while (true) {
            System.out.println(curemp.id);
            if (curemp.next == null) {
                break;
            }
            curemp = curemp.next;
        }
    }
}

class HashTab {
    private EmpLinckList[] empLinckListsArray;
    private int size;

    public HashTab(int size) {
        this.size = size;
        empLinckListsArray = new EmpLinckList[size];
        for (int i = 0; i < size; i++) {
            empLinckListsArray[i] = new EmpLinckList();
        }
    }

    //添加雇员
    public void add(Emp emp) {
        int emLinkNo = hashFun(emp.id);
        empLinckListsArray[emLinkNo].add(emp);
    }

    //遍历
    public void list() {
        for (int i = 0; i < size; i++) {
            empLinckListsArray[i].list();
        }
    }

    //编写一个散列函数
    public int hashFun(int id) {
        return id % size;
    }
}